import logging

from django.shortcuts import render

# Create your views here.
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from meiduo_mail.libs.yuntongxun.sms import CCP
from rest_framework import status
from . import constants
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger('django')
# Create your views here.
class SMSCodeView(APIView):

    def get(self,request,mobile):
        # 1.創建redis連接對象
        redis_conn = get_redis_connection('verify_codes')
        # 2.先從redis獲取發送標記
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # 3.如果取到了標記,說明此手機號頻繁發送短信
        if send_flag: # 如果取到了標記,說明此手機號頻繁發短信
            return Response({'message':'手機頻繁發送短信'},status=status.HTTP_400_BAD_REQUEST)

        # 4.生成驗證碼
        sms_code = '%06d' % randint(0,999999)
        logger.info(sms_code)

        # 創建redis管道:(把多次redis操作裝入管道中,將來一次性去執行,減少redis鏈接操作)
        pl = redis_conn.pipeline()

        # 5.把驗證碼存儲到redis數據庫
        # redis_conn.setex('sms_%s'%mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        pl.setex('sms_%s'%mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        # 6 存儲一個標記,表示此手機號已發送過短信,標記有效期60s
        # redis_conn.setex('send_flag_%s' %mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        pl.setex('send_flag_%s' %mobile,constants.SEND_SMS_CODE_INTERVAL,1)

        # 執行管道
        pl.execute()
        # import time
        # time.sleep(5)
        # 7.利用榮聯雲通訊發送短信驗證碼
        # CCP().send_template_sms(self,手機號,[驗證碼,5],temp_id=1(模板選擇1))
        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES//60],1)
        # 觸發異步任務,將異步任務添加到celery 任務隊列
        # send_sms_code(mobile,sms_code) # 調用普通函數而已
        send_sms_code.delay(mobile,sms_code) # 觸發異步任務
        # 8.響應
        return Response({'message':'ok'})



